package com.lczyfz.istep.common.utils.quartz;

import com.lczyfz.istep.common.utils.SpringContextHolder;
import com.lczyfz.istep.modules.sys.entity.ScheduleJob;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by 锋情 on 2016-11-24.
 */
public class JobExecutor {
    private static final Logger LOGGER = LoggerFactory.getLogger(JobExecutor.class);


    /**
     * 通过反射调用scheduleJob中定义的方法
     *
     * @param scheduleJob job
     */
    public static void invokeMethod(ScheduleJob scheduleJob) {
        Object object = null;
        Class clazz;
        if (StringUtils.isNotBlank(scheduleJob.getBeanName())) {
            object = SpringContextHolder.getBean(scheduleJob.getBeanName());
        } else if (StringUtils.isNotBlank(scheduleJob.getBeanClass())) {
            try {
                clazz = Class.forName(scheduleJob.getBeanClass());
                object = clazz.newInstance();
            } catch (Exception e) {
                LOGGER.error("异常！");
            }
        }
        if (object == null) {
            LOGGER.error("任务名称 = {} 未启动成功，请检查是否配置正确！", scheduleJob.getJobName());
            return;
        }
        clazz = object.getClass();
        Method method = null;
        try {
            method = clazz.getDeclaredMethod(scheduleJob.getMethodName(), ScheduleJob.class);
        } catch (NoSuchMethodException e) {
            LOGGER.error("任务名称 = {} 未启动成功，方法名设置错误", scheduleJob.getJobName());
        } catch (SecurityException e) {
            LOGGER.error("异常！");
        }
        if (method != null) {
            try {
//                method.invoke(object);
                method.invoke(object, scheduleJob);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                LOGGER.error("异常！");
            }
        }
        LOGGER.debug("任务名称 = {} 启动成功", scheduleJob.getJobName());
    }
}
